package com.shuchang.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuchang.yygh.cmn.listener.DictListener;
import com.shuchang.yygh.cmn.mapper.DictMapper;
import com.shuchang.yygh.cmn.service.DictService;
import com.shuchang.yygh.model.cmn.Dict;
import com.shuchang.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据上级id获取子节点数据列表
     *
     * @param id
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", id);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);

        //向list集合中每个dict对象中设置hasChildren
        for (Dict dict : dicts) {
            Boolean isChildren = isChildren(dict.getId());
            dict.setHasChildren(isChildren);
        }
        return dicts;
    }

    public Boolean isChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    //  导出字典列表
    @Override
    public Boolean exportData(HttpServletResponse response) {
        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            //查询数据库
            List<Dict> dictList = baseMapper.selectList(null);

            //Dict---》DictEeVo
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            }
            // 调用方法进行写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    //导入字典数据
    /**
     * 导入
     * allEntries = true: 方法调用后清空所有缓存
     * 注意缓存清空方法返回值必须为void，否则不生效哦！！！
     *
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importData(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(this)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
